<template>
  <div class="mobileBody">
    <div style="display: flex;align-items: center">
      <h4 style="margin-right: 10px">webSocket(群聊)</h4>
      <el-button size="small" type="success" @click="WebSocketConnect" v-if="!isConnect">重新连接</el-button>
      <el-button size="small" type="danger" @click="closeWebSocket" v-else>断开连接</el-button>
      <el-button size="small" type="success" @click="toPc">PC端</el-button>
      <el-button size="small" @click="logout">退出</el-button>
      <el-button type="success" :icon="Position" circle @click="toMap"/>
    </div>
    <br>
    <div class="messageBody">
      <div class="messageBox" ref="messageBoxRef">
        <div class="messageItem" v-for="item in webSocketInfo" :class="item.account === user.account ? 'infoRight' : 'infoLeft'">
          <div class="infoHalf" :class="item.account === user.account ? 'infoHalfRight' : 'infoHalfLeft'">
            <div class="messageBlock" :class="item.msg_type === 'delete' ? 'delete_msg' : ''" v-if="item.account === user.account" @contextmenu="contextmenu($event, item)">
              <span v-if="item.msg_type === 'delete'" v-html="item.message" class="msgHtml"></span>
              <el-popover
                  v-else
                  placement="right"
                  :width="100"
                  trigger="contextmenu"
              >
                <template #default>
                  <div class="withdrawClass" @click="withdraw(item)">
                    撤回
                  </div>
                </template>
                <template #reference>
                  <span v-html="item.message" class="msgHtml"></span>
                </template>
              </el-popover>
            </div>
            <img :src="item.src" class="img"/>
            <div class="messageBlock" :class="item.msg_type === 'delete' ? 'delete_msg' : ''" v-if="item.account !== user.account" @contextmenu="contextmenu($event, item)">
              <span v-if="item.msg_type === 'delete'" v-html="item.message" class="msgHtml"></span>
              <el-popover
                  v-else
                  placement="right"
                  :width="100"
                  trigger="contextmenu"
              >
                <template #default>
                  <div class="withdrawClass" @click="withdraw(item)">
                    撤回
                  </div>
                </template>
                <template #reference>
                  <span v-html="item.message" class="msgHtml"></span>
                </template>
              </el-popover>
            </div>
          </div>
        </div>
      </div>
      <div class="messageInput">
        <div style="display: none;">
          <el-input ref="inputRef" v-model="userInput"
                    type="textarea"
                    style="width: 100%" @keyup.enter="postMsg(userInput)"></el-input>
          <el-button type="primary" :disabled="!wsRef" @click="postMsg(userInput)" size="small" style="margin-left: 10px">发送</el-button>
        </div>
        <div style="display: flex;align-items: end;">
          <WangEditor :modelValue="infoRef" :toolbarConfig="toolbarConfig" @handleChange="handleChange" class="wangEditor"></WangEditor>
          <el-button type="primary" :disabled="!wsRef" @click="editPostMsg" size="small" class="mt10" style="margin-left: 10px">发送</el-button>
        </div>
      </div>
    </div>
    <div>

    </div>
  </div>
</template>

<script setup>
import {nextTick, onMounted, ref} from "vue";
import {ElMessage} from "element-plus";
import {useGlobalProperties} from "../../hooks/globalVar.js";
let {DeploymentAddress} = useGlobalProperties()
import WangEditor from "@/components/WangEditor";
import Cookies from "js-cookie"
import { formatDate } from '@/untils/untils.js'
import { httpRequest } from "@/untils/httpRequest";
const {Position} = require("@element-plus/icons-vue");

const user = JSON.parse(localStorage.getItem('user'))
// WebSocket
let wsRef = ref(null)
let webSocketInfo = ref([])
let userInput = ref('')
let inputRef = ref(null)
let isConnect = ref(false)
let messageBoxRef = ref(null)
let infoRef = ref('')
let toolbarConfig = {
  excludeKeys: [],
  toolbarKeys: [
    "emotion",
    "uploadImage",
    "color",
    "bgColor",
  ]
}
function WebSocketConnect() {
  const csrftoken = Cookies.get('csrftoken')
  if (!csrftoken) return window.location.href = "/login";
  let params = {
    opType: "chat",
    account: user.account
  }
  let paramsString = new URLSearchParams(params).toString()
  let socketUrl = process?.env?.NODE_ENV === 'development' ? ("ws://127.0.0.1:6789?" + paramsString) : (`ws://${DeploymentAddress}:6789?` + paramsString)
  // 打开一个 websocket
  wsRef.value = new WebSocket(socketUrl);
  wsRef.value.onopen = function () {
    // Web Socket 已连接上，使用 send() 方法发送数据
    isConnect.value = true
  }
  wsRef.value.onmessage = function (evt) {
    webSocketInfo.value = eval(evt.data)
    nextTick(() => {
      setScrollToBottom()
    })
  }
  wsRef.value.onclose = function () {
    // 关闭 websocket
    isConnect.value = false
    webSocketInfo.value.push({
      account: user.account,
      src: user.src,
      message: "连接已关闭...",
    })
    nextTick(() => {
      setScrollToBottom()
    })
  }
  wsRef.value.onerror = function () {
    // 通信发生错误，关闭 websocket
    isConnect.value = false
    webSocketInfo.value.push({
      account: user.account,
      message: '通信发生错误...',
    })
    nextTick(() => {
      setScrollToBottom()
    })
  }
}
function closeWebSocket() {
  wsRef.value.close()
}
function postMsg(value) {
  if (!isConnect.value) return ElMessage.error('离线了！')
  let postMsg = {
    account: user.account,
    time: formatDate(new Date()),
    message: value
  }
  wsRef.value.send(JSON.stringify(postMsg));
  nextTick(() => {
    userInput.value = ''
  })
}
function withdraw(item) {
  wsRef.value.send(JSON.stringify(item))
}
function contextmenu(event, item) {
  event.preventDefault();
}
function setScrollToBottom() {
  if (messageBoxRef.value) messageBoxRef.value.scrollTop = messageBoxRef.value?.scrollHeight
}
function handleChange(html, editor) {
  infoRef.value = editor.getHtml()
}
function editPostMsg() {
  if (!isConnect.value) return ElMessage.error('离线了！')
  let postMsg = {
    account: user.account,
    time: formatDate(new Date()),
    message: infoRef.value
  }
  wsRef.value.send(JSON.stringify(postMsg));
  nextTick(() => {
    infoRef.value = ''
  })
}
function toPc() {
  window.location.href = "/userMgr";
}
//注销登出
function logout() {
  window.location.href = "/login";
  httpRequest("post", "/user/logout", null, null, "proxy").then(res => {
    if (res?.data?.code === 200) {
      localStorage.removeItem("menu_list");
      localStorage.removeItem("user");
      ElMessage.success(res?.data?.msg)
    }
  })
}
function toMap() {
  window.location.href = "/mobile/map";
}
onMounted(() => {
  WebSocketConnect()
  setScrollToBottom()
})
</script>

<style scoped lang="less">
.mobileBody {
  width: 100%;
  height: 100vh;
  border: 1px solid #4CC6DD;
  padding: 16px;
  overflow: auto;
}
.messageBody {
  width: 100%;
  height: calc(100% - 55px);
  .messageBox {
    width: 100%;
    height: 80%;
    overflow: auto;
    border: 1px solid #e3e3e3;
    position: relative;
    .messageItem {
      width: 100%;
      min-height: 30px;
      line-height: 1.5;
      margin: 10px 0;
      .messageBlock {
        max-width: 80%;
        padding: 5px;
        background-color: #b3ecf8;
        border-radius: 3px;
        position: relative;
      }
      .img {
        width: 30px;
        height: 30px;
        margin: 0 5px;
        border-radius: 50%;
      }
    }
  }
  .messageInput {
    width: 100%;
    margin-top: 10px;
    max-height: 200px;
  }
}
.infoLeft {
  display: flex;
  justify-content: flex-start;
}
.infoRight {
  display: flex;
  justify-content: flex-end;
}
.infoHalf {
  width: 50%;
}
.infoHalfLeft {
  display: flex;
  justify-content: flex-start;
}
.infoHalfRight {
  display: flex;
  justify-content: flex-end;
}
.mt10 {
  margin-top: 10px;
}
.item_info {
  width: 100%;
  white-space: normal;
}
.delete_msg {
  background-color: white !important;
  font-size: 12px;
  color: #9EA7B4;
}
.withdrawClass {
  cursor: pointer;
}
.mobileBody .baseWangEditor {
  width: 100%;
}
</style>